#!/usr/bin/env python
# -*- coding: utf-8 -*-
# 2/10/16 base trans. wrote by srcdog on 20th, April, 2009
# ld elements in base 2, 10, 16.

import os,sys

# global definition
# base = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, F]
base = [str(x) for x in range(10)] + [ chr(x) for x in range(ord('A'),ord('A')+6)]

# bin2dec
# 二进制 to 十进制
def bin2dec(string_num):
    return str(int(string_num, 2))

# dec2bin
# 十进制 to 二进制
def dec2bin(string_num):
    num = int(string_num)
    mid = []
    while True:
        if num == 0: break
        num,rem = divmod(num, 2)
        mid.append(base[rem])

    return ''.join([str(x) for x in mid[::-1]])

def mask2bin( mask ):
    if mask > 0 and mask < 33 :
        full_1 = '11111111'+'11111111'+'11111111'+'11111111'
        full_0 = '00000000'+'00000000'+'00000000'+'00000000'
        return full_1[:mask]+full_0[mask:]
    else:
        return ""



def toIpStr( ip ):
    d = '.'
    ip = bin2dec(ip[:8])+d+bin2dec(ip[8:16])+d+bin2dec(ip[16:24])+d+bin2dec(ip[-8:])
    return ip

def ip2bin( ip ):
    full_0 = '00000000'
    parts = ip.split('.')
    p1 = dec2bin(parts[0])
    p1 = full_0[:(8-len(p1))] + p1

    p2 = dec2bin(parts[1])
    p2 = full_0[:(8-len(p2))] + p2

    p3 = dec2bin(parts[2])
    p3 = full_0[:(8-len(p3))] + p3

    p4 = dec2bin(parts[3])
    p4 = full_0[:(8-len(p4))] + p4
    
    binstr =  p1+p2+p3+p4
    return binstr

def getMaxIP(ip, mask):
    full_1 = '11111111'+'11111111'+'11111111'+'11111111'
    
    binIPStr = ip2bin( ip )
    binMaskStr = mask2bin( mask )
    
    maxIP = binIPStr[:mask] + full_1[mask:]
    return maxIP


class IpInfo(object):
    minIP = 0
    maxIP = 0

    startIP = ''
    endIP = ''

    mask = 0
    isp = ''
    desc = ''
    
    def __init__(self, info):

        info_array = info.split('/')

        if len(info_array) == 4 :
            self.startIP = info_array[0].strip()
            endDefine = info_array[1].strip()
            self.isp = info_array[2].strip()
            self.desc = info_array[3].strip()

            startIpInBin = ip2bin(self.startIP)
            endIpInBin = ''
            if str.isdigit(endDefine) :
                self.mask = int(endDefine)
                endIpInBin = getMaxIP(self.startIP, self.mask)
                self.endIP = toIpStr(endIpInBin)
            else :
                endIpInBin = ip2bin(endDefine)
            
            self.minIP = int(startIpInBin, 2)
            self.maxIP = int(endIpInBin, 2)
            print toIpStr(dec2bin(str(self.minIP))) + " " + toIpStr(dec2bin(str(self.maxIP)))
           
        
    def inThere(self,ip):
        
        iIP = int( ip2bin(ip), 2)
        if iIP <= self.maxIP and iIP >= self.minIP :
            return True
        else :
            return False

cmccIpFile = open('cmcc_ip.txt')
cmccIpList = cmccIpFile.readlines()

cmccIpInfoList = []
for cmccIp in cmccIpList :
    #print cmccIp
    cmccIpInfo = IpInfo(cmccIp)
    cmccIpInfoList.append(cmccIpInfo)

cmccIpFile.close()


ispFile = open('isp.txt', 'w')

pingResultFile = open('SubDomainResult.txt')
pingResultList = pingResultFile.readlines()
for pingResult in pingResultList :
    #print "LINE: " + pingResult
    if cmp(pingResult.strip(), '') == 0 :
        print 'Blank Line'
        continue

    tempArray = pingResult.split('\t')
    #print "Array: " + str(tempArray)
    notfoundFlag = True
    if len(tempArray) > 1 :
        for ipInfo in cmccIpInfoList :
            if ipInfo.inThere( tempArray[1] ) :
                strTemp = tempArray[0] + '\t' + tempArray[1] + '\t' + ipInfo.isp + '\t' + ipInfo.desc + '\n'
                ispFile.writelines(strTemp) 
                print strTemp  
                notfoundFlag = False
                break
    else :
        strTemp = 'Error Line: ' + pingResult[:-2] + '\n'
        ispFile.writelines(strTemp) 
        print strTemp
        notfoundFlag = False

    if notfoundFlag :
        strTemp = tempArray[0] + '\t' + tempArray[1] + '\t外网\t无备注' + '\n' 
        ispFile.writelines(strTemp) 
        print strTemp

pingResultFile.close()
ispFile.close()



#strIP = '192.168.1.1/24/内网'
#ipinfo = IpInfo( strIP )
#print ipinfo.inThere('192.168.0.1') 
#print ipinfo.inThere('192.168.1.0')
#print ipinfo.inThere('192.168.1.1')
#print ipinfo.inThere('192.168.1.254')
#print ipinfo.inThere('192.168.1.255')
#print ipinfo.inThere('192.168.2.0') 
#print ipinfo.isp


